//
//  RouteDetailTableViewController.m
//  TeamProject_Travel
//
//  Created by lanou3g on 16/4/1.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "RouteDetailTableViewController.h"
#import "RouteDetailTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "UINavigationBar+Awesome.h"
#import "DestinationDetailTableViewController.h"
#import "CDHttpHelper.h"
#import "RouteDetailModel.h"
@interface RouteDetailTableViewController ()

@property(nonatomic,strong)NSMutableArray * allDataArray;
@property(nonatomic,strong)NSMutableArray * cellDataArray;
@property(nonatomic,assign)CGFloat widthOfRow;

@end
#define NAVBAR_CHANGE_POINT 50
@implementation RouteDetailTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.allDataArray = [NSMutableArray array];
    
    [self.tableView registerClass:[RouteDetailTableViewCell class] forCellReuseIdentifier:@"routeDetail"];
    
    [self handleData];
    
}

- (void)handleData{
    [[CDHttpHelper defaultCDHttpHelper] get:[NSString stringWithFormat:@"https://chanyouji.com/api/plans/%ld.json?page=1",self.id] params:nil success:^(id responseObj) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        RouteDetailModel *model = [RouteDetailModel new];
        [model setValuesForKeysWithDictionary:dict];
        [self.allDataArray addObject:model];
        [self tableViewheaderView];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    RouteDetailModel *model = [RouteDetailModel new];
    if (self.allDataArray.count != 0) {
        model = self.allDataArray[0];
    }
    return model.plan_days.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    RouteDetailModel *model = self.allDataArray[0];
    NSDictionary *dic = model.plan_days[section];
    self.cellDataArray = [NSMutableArray array];
    [self.cellDataArray addObjectsFromArray:dic[@"plan_nodes"]];
    return self.cellDataArray.count + 1;
}

- (void)tableViewheaderView
{
    if (self.allDataArray.count != 0) {
        RouteDetailModel *model = self.allDataArray[0];
        
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i < model.plan_days.count; i++) {
            NSDictionary *dic = model.plan_days[i];
            [array addObjectsFromArray:dic[@"plan_nodes"]];
        }
        
        UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height /  3 + [self getTrueHeightWithDescription:model.descriptions])];
        
    
        // 图片
        UIImageView *headImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.frame.size.height / 3)];
        [headImage sd_setImageWithURL:[NSURL URLWithString:model.image_url]];
            [headView addSubview:headImage];
        // 标题
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,self.tableView.frame.size.height * 2 / 9, self.tableView.frame.size.width * 3 / 4, self.tableView.frame.size.height / 28)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.text = model.name;
        titleLabel.textColor = [UIColor whiteColor];
        [titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
        [headImage addSubview:titleLabel];
        
        // 副标题
        UILabel *subheadLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,self.tableView.frame.size.height * 4 / 15, self.tableView.frame.size.width * 3 / 4, self.tableView.frame.size.height / 28)];
        subheadLabel.backgroundColor = [UIColor clearColor];
        

        subheadLabel.text = [NSString stringWithFormat:@"%ld天/%ld个旅行地",model.plan_days.count,array.count];
       
        
        subheadLabel.textColor = [UIColor whiteColor];
        [headImage addSubview:subheadLabel];
        
        
        UILabel *descriptionLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, self.tableView.frame.size.height / 3, [UIScreen mainScreen].bounds.size.width - 30, [self getTrueHeightWithDescription:model.descriptions])];
        descriptionLabel.numberOfLines = 0;
        descriptionLabel.text = model.descriptions;
        [headView addSubview:descriptionLabel];
    
    self.tableView.tableHeaderView = headView;
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RouteDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"routeDetail" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[RouteDetailTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"routeDetail"];
    }
    
    
    
    if (self.allDataArray.count != 0) {
        RouteDetailModel *model = self.allDataArray[0];
        NSDictionary *dic = model.plan_days[indexPath.section];
        NSMutableArray *array = [NSMutableArray array];
        [array addObjectsFromArray:dic[@"plan_nodes"]];
        
        
        if (indexPath.row == 0) {
            cell.typeView.image = [UIImage imageNamed:@"note_route.png"];
            cell.titleLabel.text = @"今日备忘";
            [cell.backImageView removeFromSuperview];
            cell.descriptionLabel.frame = CGRectMake(15, CGRectGetMaxY(cell.titleLabel.frame) + 5, [UIScreen mainScreen].bounds.size.width - 30, [self getTrueHeightWithDescription:dic[@"memo"]]);
            cell.descriptionLabel.text = dic[@"memo"];
            
            self.widthOfRow =[self getTrueHeightWithDescription:dic[@"memo"]] + 60;
                                           
        }else{
            NSDictionary *dict = array[indexPath.row - 1];
            if ([dict[@"entry_type"] isEqualToString:@"Attraction"]) {
                cell.typeView.image = [UIImage imageNamed:@"location_route.png"];
            }else{
                cell.typeView.image = [UIImage imageNamed:@"travel_route.png"];
            }
            
            cell.titleLabel.text = dict[@"entry_name"];
            cell.backImageView.frame = CGRectMake(10, CGRectGetMaxY(cell.titleLabel.frame) + 5, [UIScreen mainScreen].bounds.size.width - 20, [UIScreen mainScreen].bounds.size.width / 2);
            [cell.contentView addSubview:cell.backImageView];
            
            
            if (![dict[@"image_url"] isKindOfClass:[NSNull class]]) {
                cell.backImageView.frame = CGRectMake(10, CGRectGetMaxY(cell.titleLabel.frame) + 5, [UIScreen mainScreen].bounds.size.width - 20, [UIScreen mainScreen].bounds.size.width / 2);
                [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:dict[@"image_url"]]];
                
                self.widthOfRow = [UIScreen mainScreen].bounds.size.width / 2 + [self getTrueHeightWithDescription:dict[@"tips"]] + 60;
                
            }else{
                cell.backImageView.frame = CGRectMake(15, CGRectGetMaxY(cell.titleLabel.frame) + 5, 0, 0);
                
                self.widthOfRow = [self getTrueHeightWithDescription:dict[@"tips"]] + 60;
                
            }
            cell.descriptionLabel.frame = CGRectMake(15, CGRectGetMaxY(cell.backImageView.frame) + 5, [UIScreen mainScreen].bounds.size.width - 30, [self getTrueHeightWithDescription:dict[@"tips"]]);
            cell.descriptionLabel.text = dict[@"tips"];
            
            
        }
        
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row != 0) {
        if (self.allDataArray.count != 0) {
            RouteDetailModel *model = self.allDataArray[0];
            NSDictionary *dic = model.plan_days[indexPath.section];
            NSMutableArray *array = [NSMutableArray array];
            [array addObjectsFromArray:dic[@"plan_nodes"]];
            NSDictionary *dict = array[indexPath.row - 1];
            DestinationDetailTableViewController *desVC = [[DestinationDetailTableViewController alloc]init];
            desVC.ID = [dict[@"entry_id"] integerValue];
            [self.navigationController pushViewController:desVC animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    NSString *string;
    if (self.allDataArray.count != 0) {
        RouteDetailModel *model = self.allDataArray[0];
        NSDictionary *dic = model.plan_days[section];
        NSMutableArray *array = [NSMutableArray array];
        [array addObjectsFromArray:dic[@"plan_nodes"]];
        NSDictionary *dict = array[0][@"destination"];
        NSString *name = dict[@"name_zh_cn"];
        string = [NSString stringWithFormat:@"DAY%ld  %@",section + 1,name];
    }
    
    
    return string;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.widthOfRow;
}

- (CGFloat)getTrueHeightWithDescription:(NSString *)discuss
{
    CGRect rect = [discuss boundingRectWithSize:(CGSizeMake([UIScreen mainScreen].bounds.size.width, 200000)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]} context:nil];
    return rect.size.height;
}


//去除navigation显示
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UIColor * color = [UIColor colorWithRed:0 green:191/255.0 blue:255/255.0 alpha:1];
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > NAVBAR_CHANGE_POINT) {
        CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    } else {
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self scrollViewDidScroll:self.tableView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar lt_reset];
}
@end
